package com.zhangmeng.tools.controller;

import com.zhangmeng.tools.utils.AlertUtils;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-06-13 10:56
 */
@Slf4j
public class WebSocketClientController {

    @FXML
    public TextField ip;

    @FXML
    public TextField port;

    @FXML
    public Button conn;

    @FXML
    public Button send;

    @FXML
    public TextField content;

    @FXML
    public TextField params;

    @FXML
    private TextArea show_result;

    private WebSocketClient webSocketClient;

    public static ObservableList<String> message_list = FXCollections.observableArrayList();

    @FXML
    public void initialize() {

        if (ip.getText().length() == 0){
            ip.setText("localhost");
        }

        if (port.getText().length() == 0){
            port.setText("3333");
        }

        if (params.getText().length() == 0){
            params.setText("/websocketchart?userId=1&source=pc");
        }

        conn.setOnAction(event -> {
            getConnection();
        });

        message_list.addListener((ListChangeListener<String>) c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (String s : message_list) {
                        stringBuilder.append(s);
                    }
                    receive(stringBuilder.toString());
                }
            }
        });

        send.setOnAction(event -> {
            webSocketClient.send(content.getText());
        });
    }

    public void receive(String msg) {
        Platform.runLater(() -> {
            this.show_result.setText(msg);
        });
    }


    private void getConnection() {
        if (webSocketClient == null) {
            webSocketClient(ip.getText(), Integer.parseInt(port.getText()),params.getText());
        }else {
            if (!webSocketClient.isOpen()){
                webSocketClient(ip.getText(), Integer.parseInt(port.getText()),params.getText());
            }
        }
    }

    public void webSocketClient(String socket_address, int socket_port,String params) {

        String url = "ws://" + socket_address + ":" + socket_port+params;
        log.info(url);
        try {
            webSocketClient = new WebSocketClient(new URI(url), new Draft_6455()) {
                //连接服务端时触发
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    add_msg("websocket客户端和服务器连接成功!");
                }

                //收到服务端消息时触发
                @Override
                public void onMessage(String message) {
                    add_msg(message);
                }

                //和服务端断开连接时触发
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    add_msg("websocket客户端退出连接");
                }

                //连接异常时触发
                @Override
                public void onError(Exception ex) {
                    add_msg("websocket客户端和服务器连接发生错误={" + ex.getMessage() + "}");
                }
            };
            webSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void add_msg(String msg) {
        message_list.add(msg);
        message_list.add(System.lineSeparator());
    }
}
